package com.rao.gmall.product.component;

import com.rao.gmall.product.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author nzmxfan
 * @create 2021-08-05-12:13
 */
@Component
public class MinioService {

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioConfig minioConfig;

    public String upload(InputStream inputStream, String bucketName, String fileName) throws Exception {

        if (StringUtils.isEmpty(bucketName)){
            // 该桶名不存在，使用默认桶
            bucketName = minioConfig.getDefaultBucket();
        }else {
            // 如果 桶名存在，则确认桶是否存在，不存在则创建同名桶
            if (!minioClient.bucketExists(bucketName)){
                minioClient.makeBucket(bucketName);
            }
        }
        // 生成文件名
        fileName = UUID.randomUUID().toString().replace("-","") + "_" +fileName;

        // 根据属性上传文件
        PutObjectOptions options = new PutObjectOptions(inputStream.available(), -1);
        minioClient.putObject(bucketName, fileName, inputStream, options);
        //返回文件所存储的地址
        String url = minioConfig.getUrl() + "/" + bucketName + "/" + fileName;
        return url;
    }
}
